package com.irdstudio.apicenter.frame.web;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * MACCS中视图渲染辅助类
 * 
 * @author guangming.li
 * @version 1.0
 * @date 2015-05-24
 */
public class MacmsRenderUtil {

	/* 无效请求 */
	public final static int INVALID_REQUEST = 2010;
	/* 该交易无效，不在通讯总线处理范围之内 */
	public final static int OUT_OF_RANGE = 2011;
	/* 通讯控制总线初始化失败 */
	public final static int INITIALIZE_BUS_FAIURE = 9001;
	/* 交易处理类未找到 */
	public final static int TRADE_CLASS_NOT_FOUND = 9002;
	/* 交易处理类实例化异常 */
	public final static int TRADE_CLASS_EXCEPTION = 9003;
	/* 交易处理自定义异常代码 */
	public final static int CUSTOM_EXCEPTION = 9999;

	/* 错误信息定义 */
	private final static Map<Integer, String> errMsgs = new HashMap<Integer, String>();
	static {
		errMsgs.put(2010, "无效的请求!");
		errMsgs.put(2011, "该交易无效，不在通讯总线处理范围之内!");
		errMsgs.put(9010, "通讯控制总线初始化失败!");
		errMsgs.put(9002, "交易处理类未找到!");
		errMsgs.put(9003, "交易处理类实例化异常!");
	}

	/* 文本日志对象 */
	private final static Logger logger = LoggerFactory
			.getLogger(MacmsRenderUtil.class);

	/**
	 * 返回标准的错误信息(JSON格式)
	 * 
	 * @param errorCode
	 * @param response
	 */
	public static void renderNormalErrorJsonView(Integer normalErrCode,
			HttpServletResponse response) {
		String errMsg = errMsgs.get(normalErrCode);
		if (errMsg == null) {
			renderCustomErrorJsonView("9999", "未找到有效的错误码信息!", response);
		} else {
			renderCustomErrorJsonView(normalErrCode.toString(), errMsg,
					response);
		}

	}

	/**
	 * 返回自定义错误信息(JSON格式)
	 * 
	 * @param errorCode
	 * @param errorMsg
	 * @param response
	 */
	public static void renderCustomErrorJsonView(String errCode, String errMsg,
			HttpServletResponse response) {
		Map<String, Object> m = new HashMap<String, Object>();
		m.put("ec", errCode);
		m.put("em", errMsg);
		logger.error("错误码:" + errCode + ",原因:" + errMsg);
		try {
			new ObjectMapper().getJsonFactory().createJsonGenerator(
					response.getOutputStream(), JsonEncoding.UTF8).writeObject(
					m);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
